import request from '@renderer/utils/request';
import { IpcAPI, WebSocketConnectionEvent, WebSocketDisconnectionEvent, WebSocketMessageEvent, ProgressEvent, CompleteEvent, ErrorEvent } from '../types/ipc';

class WebAdapter implements IpcAPI {
  

  // 这里实现 Web 特定的通信逻辑
  // 当迁移到 Web 时，你需要填充这些方法

  log = {
    info: (message: string, ...args: any[]): void => {
      console.log('[Web] INFO:', message, ...args);
    },
    warn: (message: string, ...args: any[]): void => {
      console.warn('[Web] WARN:', message, ...args);
    },
    error: (message: string, ...args: any[]): void => {
      console.error('[Web] ERROR:', message, ...args);
    },
    debug: (message: string, ...args: any[]): void => {
      console.debug('[Web] DEBUG:', message, ...args);
    }
  };

  downloadFile(payload: any): void {
    console.log('[Web] downloadFile called', payload);
    // Web 实现将在这里
  }

  saveBase64Image(params: { base64Data: string; directory: string; fileName: string; imagesPath: string }): Promise<any> {
    console.log('[Web] saveBase64Image called', params);
    return Promise.resolve();
  }
  readMetadata(filePath: string|File,map?:object): Promise<any> {
    const formData = new FormData();
    if (filePath instanceof File) {
      formData.append('file', filePath);
    }
    formData.append('map', JSON.stringify(map));
    return request({
      url: '/command/read-metadata',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => {
      return res.data;
    }).catch(error => {
      return Promise.reject(error);
    });
  }
  readFolderMeta(): Promise<any> { return Promise.resolve(); }
  openFileDialog(): Promise<any> { return Promise.resolve(); }
  selectFileFolder(): Promise<any> { return Promise.resolve(); }
  openFileFolder(folderPath: string): Promise<any> { return Promise.resolve(); }
  scanDirectories(targetPath: string): Promise<any> { return Promise.resolve(); }
  scanImages(basePath: string, folderName: string): Promise<any> { return Promise.resolve(); }
  scanLoras(loraPath: string): Promise<any> { 
    return request({
      url: '/command/get-loras',
      method: 'get',
    }).then(res=>{
      return res.data
    }).catch(error => {
      return Promise.reject(error);
    })
  }
  // 获取Lora配置
getLoraConfig(loraPath: string): Promise<any> {
  return request({
    url: '/command/get-lora-json',
    method: 'get',
    params: { loraPath } // 将路径作为查询参数传递
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
}

// 保存Lora配置
saveLoraConfig(loraPath: string, data: any): Promise<any> {
  return request({
    url: '/command/save-lora-config',
    method: 'post',
    data: { 
      loraPath: loraPath,  // Lora路径
      data: data           // 配置数据（包装在data字段中）
    }
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
}

// 保存Lora图片
saveLoraImage(imagePath: string | File, loraPath: string): Promise<any> {
  const formData = new FormData();
  
  // 处理文件对象，统一命名为file
  if (imagePath instanceof File) {
    formData.append('file', imagePath);
  }
  
  // 添加其他参数
  formData.append('loraPath', loraPath);
  
  return request({
    url: '/command/save-lora-image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
}

// 保存为WebP图片 - 表单形式
saveWebpImage: (imagePath: string | File, targetPath: string) => Promise<any> = (imagePath, targetPath) => {
  const formData = new FormData();
  
  // 处理文件对象，统一命名为file
  if (imagePath instanceof File) {
    formData.append('file', imagePath);
  }
  
  // 添加其他参数
  formData.append('targetPath', targetPath);
  
  return request({
    url: '/command/save-webp-image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
};

// 缓存图片
cacheImage: (cachePath: string, array: ArrayBuffer|File) => Promise<any> = (cachePath, array) => {
  const formData = new FormData();
  if (array instanceof File) {
    formData.append('file', array);
  }
  formData.append('cachePath',cachePath);
  return request({
    url: '/command/cache-image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
};

// 获取Lora元数据
getLoraMetadata(loraPath: string): Promise<any> {
  return request({
    url: '/command/get-lora-metadata',
    method: 'get',
    params: { loraPath }
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
}

// 获取Civitai元数据
getCivitaiMetadata(sha256: string | undefined, loraPath: string, replaceCover: boolean | undefined): Promise<any> {
  return request({
    url: '/command/fetch-civitai-info',
    method: 'post',
    data: {
      sha256,
      loraPath,
      replaceCover
    }
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
}
  localSet(key: string, value: any): Promise<any> { return Promise.resolve(); }
  localGet(key: string): Promise<any> { return Promise.resolve(); }
  localRemove(key: string): Promise<any> { return Promise.resolve(); }
  localClear(): Promise<any> { return Promise.resolve(); }
  sessionSet(key: string, value: any): Promise<any> { return Promise.resolve(); }
  sessionGet(key: string): Promise<any> { return Promise.resolve(); }
  sessionRemove(key: string): Promise<any> { return Promise.resolve(); }
  sessionClear(): Promise<any> { return Promise.resolve(); }
getGlobalConfig(): Promise<any> {
  return request({
    url: '/command/get-config-json',
    method: 'get'
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
}

// 保存全局配置
saveConfig(config: any): Promise<any> {
  return request({
    url: '/command/save-config',
    method: 'post',
    data: config 
  }).then(res => {
    return res.data;
  }).catch(error => {
    return Promise.reject(error);
  });
}
  sendWebsocketData(data:any,type:string): Promise<any> { return Promise.resolve(); }
  broadcastMessage(message: string): Promise<any> { return Promise.resolve(); }
  sendToClient(clientId: string, message: string,type: string): Promise<any> { return Promise.resolve(); }
  getSocketClients(): Promise<any> { return Promise.resolve(); }

  onWebSocketConnection(callback: (event: WebSocketConnectionEvent) => void): () => void {
    console.log('[Web] onWebSocketConnection registered');
    return () => {}; // 返回清理函数
  }

  onWebSocketDisconnection(callback: (event: WebSocketDisconnectionEvent) => void): () => void {
    console.log('[Web] onWebSocketDisconnection registered');
    return () => {};
  }

  onWebSocketMessage(callback: (event: WebSocketMessageEvent) => void): () => void {
    console.log('[Web] onWebSocketMessage registered');
    return () => {};
  }

  onDownloadProgress(callback: (progress: any) => void): () => void {
    console.log('[Web] onDownloadProgress registered');
    return () => {};
  }

  onDownloadComplete(callback: (result: any) => void): () => void {
    console.log('[Web] onDownloadComplete registered');
    return () => {};
  }

  onDownloadError(callback: (error: any) => void): () => void {
    console.log('[Web] onDownloadError registered');
    return () => {};
  }

  onCsvImportProgress(callback: (progress: any) => void): void {
    console.log('[Web] onCsvImportProgress registered');
  }

  onExportProgress(callback: (data: ProgressEvent) => void): () => void {
    console.log('[Web] onExportProgress registered');
    return () => {};
  }

  onExportComplete(callback: (data: CompleteEvent) => void): () => void {
    console.log('[Web] onExportComplete registered');
    return () => {};
  }

  onExportError(callback: (data: ErrorEvent) => void): () => void {
    console.log('[Web] onExportError registered');
    return () => {};
  }

  onImportProgress(callback: (progress: any) => void): () => void{
    console.log('[Web] onExportError registered');
    return () => {};
  }
}

export default WebAdapter;
